<?php

/**
 * This is the model class for table "tbl_article".
 *
 * The followings are the available columns in table 'tbl_article':
 * @property integer $id
 * @property integer $zone_id
 * @property integer $version
 * @property integer $approved
 * @property integer $edited
 * @property integer $archived
 * @property integer $protected
 * @property string $headline
 * @property string $source
 * @property integer $topic_id
 * @property integer $author_id
 * @property string $body
 * @property integer $editor_id
 * @property integer $approver_id
 * @property string $update_time
 * @property string $create_time
 *
 * The followings are the available model relations:
 * @property Zone $zone
 * @property User $author
 * @property User $editor
 * @property User $approver
 * @property Topic $topic
 */
class Article extends SeoVietActiveRecord
{
        const YES = 1;
        const NO = 0;

        //autoset author_id (NO updater_id)
        protected function beforeValidate(){
            if ($this->isNewRecord){
                $this->author_id = Yii::app()->user->id;
            }
            else
                $this->version ++;
            return parent::beforeValidate();
        }

        //find all topic to set on dropdown list
        public function getTopicOptions(){
//            $topics = Topic::model()->findAll();
//            $topic_names = array();
//            foreach ($topics as $topic){
//                $topic_names[$topic->id] = $topic->name;
//            }
//            return $topic_names;
            $topic_names = CHtml::listData( Topic::model()->findAll(), 'id', 'name');
            return $topic_names;
        }

        public function getZoneOptions(){
//            $zones = Zone::model()->findAll();
//            $zone_names = array();
//            foreach ($zones as $zone){
//                $zone_names[$zone->id] = $zone->title    ;
//            }
//            return $zone_names;
            $zone_names = CHtml::listData( Zone::model()->findAll(), 'id', 'title');
            return $zone_names;
        }

        public function getYesNoOptions(){
            return array(
                self::NO => 'No',
                self::YES=> 'Yes',
            );
        }

        //based on Editor Role
        public function getEditorOptions(){
            $editors = CHtml::listData( User::model()->findAll(), 'id', 'username');
            return $editors;
        }

        public function getApproverOptions(){
            $approvers = CHtml::listData( User::model()->findAll(), 'id', 'username');
            return $approvers;
        }


        public function getZoneText(){
            $zoneOptions = $this->getZoneOptions();
            return isset($zoneOptions[$this->zone_id]) ?
                    $zoneOptions[$this->zone_id] :
                    "unknown zone ({$this->zone_id})";
        }
        

        public function getApprovedText(){
            $approvedOptions = $this->getYesNoOptions();
            return isset($approvedOptions[$this->approved]) ?
                    $approvedOptions[$this->approved] :
                    "unknown approved status ({$this->approved})";
        }

        public function getEditedText(){
            $editedOptions = $this->getYesNoOptions();
            return isset($editedOptions[$this->edited]) ?
                    $editedOptions[$this->edited] :
                    "unknown edited status ({$this->edited})";
        }

        public function getArchivedText(){
            $archivedOptions = $this->getYesNoOptions();
            return isset($archivedOptions[$this->archived]) ?
                    $archivedOptions[$this->archived] :
                    'Unknown status';
        }

        public function getProtectedText(){
            $protectedOptions = $this->getYesNoOptions();
            return isset($protectedOptions[$this->protected]) ?
                    $protectedOptions[$this->protected] :
                    "Unknown status";
        }

        public function getTopicText(){
            $topicOptions = $this->getTopicOptions();
            return isset($topicOptions[$this->topic_id]) ?
                    $topicOptions[$this->topic_id] :
                    "Unknown topic ({$this->topic_id})";
        }

        public function getAuthorText(){
            return isset($this->author_id) ?
                    $this->author->username :
                    "Unknown author";
        }

        public function getApproverText(){
            $approverOptions = $this->getApproverOptions();
            return isset($approverOptions[$this->approver_id]) ?
                    $approverOptions[$this->approver_id] :
                    "No one";
        }

        public function getEditorText(){
            $editorOptions = $this->getEditorOptions();
            return isset($editorOptions[$this->editor_id]) ?
                    $editorOptions[$this->editor_id] :
                    "No one";
        }

        public function getAllUserOptions(){
            $allUserOptions = CHtml::listData(User::model()->findAll(), 'id', 'username');
            return $allUserOptions;
        }

        public function getUserRoleOptions(){
            $userroles =  CHtml::listData(Yii::app()->authManager->getRoles(), 'name', 'name');

            //delete admin from result
            //prevent choosing admin
            $position = array_search("ADMIN", $userroles);
            unset ($userroles[$position]);

            //delete 'author' from result
            //prevent changing the author
            unset ($userroles[array_search("author", $userroles)]);


            //if user is APPROVER (NOT ADMIN) -> only 1 choice: set editor
            if ( !Yii::app()->user->checkAccess('ADMIN') ){
                unset ($userroles[array_search("approver", $userroles)]);
            }
            
            return $userroles;
        }

       
        public function associateUserToArticle($user){
            $sql = "INSERT INTO tbl_article_user_assignment ( user_id, article_id)
                VALUES (:userId, :articleId)";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue('userId', $user->id, PDO::PARAM_INT);
            $command->bindValue("articleId", $this->id, PDO::PARAM_INT);
            return $command->execute();
        }

        public function isUserInArticle($user){
            $sql = "SELECT user_id FROM tbl_article_user_assignment WHERE
                article_id=:articleId AND user_id=:userId";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue("articleId", $this->id, PDO::PARAM_INT);
            $command->bindValue("userId", $user->id, PDO::PARAM_INT);
            return $command->execute()==1 ? true : false;
        }


	/**
	 * Returns the static model of the specified AR class.
	 * @return Article the static model class
	 */
         public function associateUserToRole($role,$userId)
         {
             $sql="INSERT INTO tbl_article_user_role(user_id,article_id,role) VALUES(:userId, :articleId,:role)" ;
             $command=Yii::app()->db->createCommand($sql);
             $command->bindValue(":userId",$userId,PDO::PARAM_INT);
             $command->bindValue(":articleId",$this->id,PDO::PARAM_INT);
             $command->bindValue(":role",$role,PDO::PARAM_STR);
             return $command->execute();//return number of row effected
         }
           public function removeUserFromRole($role,$userId)
         {
             $sql="DELETE FROM tbl_article_user_role WHERE user_id=:userId AND article_id=:articleId AND role=:role" ;
             $command=Yii::app()->db->createCommand($sql);
             $command->bindValue(":userId",$userId,PDO::PARAM_INT);
             $command->bindValue(":articleId",$this->id,PDO::PARAM_INT);
             $command->bindValue(":role",$role,PDO::PARAM_STR);
             return $command->execute();//return number of row effected
         }
         public function isUserInRole($role)
         {
             $sql="SELECT role FROM tbl_article_user_role WHERE user_id=:userId AND article_id=:articleId AND role=:role";
             $command=Yii::app()->db->createCommand($sql);
             $command->bindValue(":userId",Yii::app()->user->getId(),PDO::PARAM_INT);//get current user
             $command->bindValue(":articleId",$this->id,PDO::PARAM_INT);
             $command->bindValue(":role",$role);
            return $command->execute()==1 ? true : false;
         }

         
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_article';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('zone_id, headline, topic_id, body', 'required'),
			array('id, zone_id, version, approved, edited, archived, protected, topic_id, author_id, editor_id, approver_id', 'numerical', 'integerOnly'=>true),
			array('headline, source', 'length', 'max'=>128),
			array('update_time, create_time', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, zone_id, version, approved, edited, archived, protected, headline, source, topic_id, author_id, body, editor_id, approver_id, update_time, create_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'zone' => array(self::BELONGS_TO, 'Zone', 'zone_id'),
			'author' => array(self::BELONGS_TO, 'User', 'author_id'),
			'editor' => array(self::BELONGS_TO, 'User', 'editor_id'),
			'approver' => array(self::BELONGS_TO, 'User', 'approver_id'),
			'topic' => array(self::BELONGS_TO, 'Topic', 'topic_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'zone_id' => 'Zone',
			'version' => 'Version',
			'approved' => 'Approved',
			'archived' => 'Archived',
                        'edited'    => 'Edited',
			'protected' => 'Protected',
			'headline' => 'Headline',
			'source' => 'Source',
			'topic_id' => 'Topic',
			'author_id' => 'Author',
			'body' => 'Body',
			'editor_id' => 'Editor',
			'approver_id' => 'Approver',
			'update_time' => 'Update Time',
			'create_time' => 'Create Time',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('zone_id',$this->zone_id);
		$criteria->compare('version',$this->version);
		$criteria->compare('approved',$this->approved);
		$criteria->compare('archived',$this->archived);
                $criteria->compare('edited', $this->edited);
		$criteria->compare('protected',$this->protected);
		$criteria->compare('headline',$this->headline,true);
		$criteria->compare('source',$this->source,true);
		$criteria->compare('topic_id',$this->topic_id);
		$criteria->compare('author_id',$this->author_id);
		$criteria->compare('body',$this->body,true);
		$criteria->compare('editor_id',$this->editor_id);
		$criteria->compare('approver_id',$this->approver_id);
		$criteria->compare('update_time',$this->update_time,true);
		$criteria->compare('create_time',$this->create_time,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
}